#!/bin/bash
. ./var
. ./Install_trash
. ./Add_Users
. ./Install_zabbix_agent
. ./System_Security
Initialize_a_new_CentOS_Server(){
#检查是不是CentOS7,不是就退出脚本
    echoRed "检查是不是CentOS7,不是就退出脚本"
    grep "release 7" /etc/redhat-release
    if  [ $? = 0 ] ; then
        echoGreen "这是CentOS7，可以用该脚本初始化"
    else
	rm -rf $dir
        exit 6
    fi
    echoYellow "----------------------------------------------"
    sleep 6
#调用Add_Users
    echoRed "添加普通用户"
    Add_Users
    
    echoYellow "----------------------------------------------"
    sleep 6
#ssh优化
    echoRed "ssh优化,修改ssh port、禁止root用户远程登录"
    #sed -i 's/#Port 22/Port 10036/g' /etc/ssh/sshd_config && systemctl restart sshd
    #yum install iptables-services  -y && systemctl stop  iptables && systemctl disable   iptables
    #/sbin/iptables -I INPUT -p tcp --dport 10036 -j ACCEPT && /sbin/iptables -I INPUT -p tcp --dport 80  -j ACCEPT
    #service iptables save

    echoGreen "ssh优化完成"

    echoYellow "----------------------------------------------"
    sleep 6

#配置国内的阿里源，并安装基础软件包
    echoRed "配置国内的阿里源，并安装基础软件包"
    yum install wget -y
    if [ $? != 0 ];then
        echoRed "wget未安装成功,即将退出"
        exit 31
       
    else
        echoGreen "wget安装成功，继续配置……"
    fi 
    #yum install -y epel-release
    [ -f /etc/yum.repos.d/epel.repo ] || wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
    [ -f /etc/yum.repos.d/CentOS-Base.repo ] && mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup && wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
    yum clean all && yum makecache fast && yum repolist && yum update -y
    yum -y install lrzsz net-tools vim curl wget 
    yum -y install unzip git expect ntpdate lsof bash-completion tree

    echoGreen "阿里源配置完成，基础软件包已完成安装"
    echoYellow "----------------------------------------------"
    sleep 6
#修改时区，更新时间
    echoRed "修改时区，更新时间"
    timedatectl set-timezone Asia/Shanghai && /usr/sbin/ntpdate -u ntp1.aliyun.com  &> /dev/null
    #如果以*开头的说明已经与ntp服务器同步了
    chronyc sources
    echo "#update time" >> /var/spool/cron/root
    #echo "/usr/sbin/ntpdate -u ntp1.aliyun.com  &> /dev/null" >> /var/spool/cron/root
    echo "*/3 * * * *  /usr/sbin/ntpdate  -u ntp1.aliyun.com  &> /dev/null " >> /var/spool/cron/root
    
    systemctl restart crond.service
    echoGreen "时间已完成同步"
    echoYellow "----------------------------------------------"
    sleep 6

#防火墙,selinux
    cd /tmp 
    echoRed "关闭firewalld，selinux"
    getenforce && setenforce 0 && getenforce && sed -i  's/SELINUX=enforcing/SELINUX=disabled/g'  /etc/selinux/config
    systemctl status firewalld && systemctl stop firewalld && systemctl disable firewalld && systemctl status firewalld

    echoGreen "firewalld、selinux已完成关闭，selinux需要重启服务器才能显示为disabled"
    
    pwd
    pwd
    pwd

    echoYellow "----------------------------------------------"
    sleep 6
#调整文件描述符的数量
    echoRed "调整文件描述符的数量"
	#aliyun这里已经配置了limits
    #echo -e "* soft nofile 65535\nroot hard nofile 65535\n* soft nproc 65535\n* hard nproc 65535\n" >> /etc/security/limits.conf
    sed -i 's#4096#65535#g' /etc/security/limits.d/20-nproc.conf
    ulimit -u 65535 #3803
    ulimit -n 65535 
    tail /etc/security/limits.conf

    echoGreen "limits以调整完成，需要重新连接终端才能显示设置后的值"
    echoYellow "----------------------------------------------"
    sleep 6

#精简开机启动服务
    pwd
    pwd
    pwd
    cd /
    echoRed "精简开机启动服务"
    chkconfig network on
    systemctl enable sshd  chronyd crond rsyslog #sysstat
    systemctl disable postfix && systemctl stop  postfix

    echoGreen "已完成"

    pwd
    pwd
    pwd

    echoYellow "----------------------------------------------"
    sleep 6
#内核参数优化    
    echoRed "内核参数优化"
    #先备份之前的内核参数，然后配置内核参数
    cp /etc/sysctl.conf /etc/sysctl.conf.bak && wget -O /etc/sysctl.conf https://download.gobgm.com/file/All_conf/sysctl.conf
    sysctl -p
    sleep 6
    tail  /etc/sysctl.conf
    sysctl -p
    echoGreen "内核优化已完成"
    echoYellow "----------------------------------------------"
#更改字符集，支持中文，但建议还是用英文字符集，防止乱码

    sleep 3
    sleep 3

    echoYellow "----------------------------------------------"
#清空/etc/issue，/etc/motd
    echoRed "清空/etc/issue /etc/motd"
    cp /etc/issue /etc/issue.bak && > /etc/issue
    cp /etc/motd /etc/motd.bak && > /etc/motd
cat > /etc/motd << EOF
Warning!  If unauthorized, illegal login system, please quit immediately!!
Your system fingerprint has been recorded!!
EOF

cat > /etc/issue << EOF
Warning!  If unauthorized, illegal login system, please quit immediately!!
Your system fingerprint has been recorded!!
EOF
    echoGreen "登录警告提示已完成!!!"
    echoYellow "----------------------------------------------"
    sleep 6

#清除多余的系统虚拟账号
    sleep 6
#为grub菜单加密
    sleep 6
#命令历史记录优化
    #报错shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory
    #解决：该错误表示 getcwd 命令无法定位到当前工作目录。一般来说是因为你 cd 到了某个目录之后 rm 了这个目录，这时去执行某些 service 脚本的时候就会报 getcwd 错误。只需要 cd 到任何一个实际存在的目录下在执行命令即可
    #https://blog.csdn.net/arlanhon/article/details/18940579
    pwd
    pwd
    pwd

    cd /
    echoRed "命令历史记录优化"
    echo "export HISTTIMEFORMAT=\"\`whoami\` : %F %T :\"" >> /etc/profile && source /etc/profile
    #echo "export  HISTSIZE=200"  >>  /etc/profile   && source /etc/profile
    sed -i 's/HISTSIZE=1000/HISTSIZE=500/g' /etc/profile && source /etc/profile
    
    source /etc/profile && source /etc/profile
    #sed -i 's/\\u@\\h\ /\\u@\\H\ /g' /etc/bashrc

    echoGreen "已完成优化，需要重启连接才能有效"
    echoYellow "----------------------------------------------"
    sleep 6

    pwd
    pwd
#修改主机名
    echoRed "更改主机名，新主机名格式：Aliyun-IP地址的最后一位-SERVER"
    hostnameip=$(hostname -I)
    #因为我装了docker，所有有很多ip，这里我用awk取的第一个ip
    #hostnameip=$(hostname -I | awk -F' ' '{print $1}')
    #int=$(ls /etc/sysconfig/network-scripts/ifcfg-*   | grep -v lo)
    #Error: NetworkManager is not running.需要开启systemctl start NetworkManager服务，才能使用nmcli
    #eth=$(nmcli dev status | grep connected | awk '{print $1}')
    New_hostname=$(echo "aliyun-"$(echo $hostnameip|awk -F'.' '{print $4}')"-SERVER")
    echo "当前IP地址： "[$hostnameip]
    #echo "网卡名称：   "${eth}
    #echo "网络文件路径： "$int
    echo "当前主机名："$(hostname)
    echo "新主机名为："${New_hostname}
    #更改主机名
    echoGreen "----------------------------------------------------"
    echoRed "-----------------即将更改主机名---------------------"
    hostnamectl set-hostname ${New_hostname}
    echoGreen "$(hostname)"
    echoGreen "重新登录就会显示更改后的主机名"

    echoYellow "----------------------------------------------"
    sleep 6
#配置回收站
    pwd
    pwd
    pwd

    echoRed "配置回收站"
    #因为Add_Users调用完成时，删除了$dir,所有不能直接调用函数，会丢失目录。我们在把$dir创建出来
    cd /
    pwd && pwd && trash
    cd /
    echoGreen "配置回收站完成"
    echoYellow "----------------------------------------------"
    sleep 6
#安装监控系统并加入    
   pwd
   pwd
   pwd
   cd /tmp
   echoRed "安装监控软件"
   /usr/sbin/zabbix_agentd -V &>/dev/null || zabbix_agent

   pwd
   
   cd
   pwd

   echoYellow "----------------------------------------------"
   sleep 6

#系统优化项
    System_Security
#锁定关键系统文件,限制日志文件
    echoRed "锁定关键系统文件，会导致锁定的文件不能进行写操作。如果需要写入，进行解锁文件就ok了"
    chattr +i /etc/passwd /etc/shadow /etc/group /etc/gshadow
    
    chattr +a /var/log/dmesg /var/log/cron /var/log/lastlog /var/log/messages /var/log/secure /var/log/wtmp

    #解锁文件
    #chattr -i /etc/passwd /etc/shadow /etc/group /etc/gshadow
    #lsattr /etc/passwd /etc/shadow /etc/group /etc/gshadow |grep "i"  && echoGreen "关键的系统文件已经锁定"
    #查看锁定的文件
    lsattr /etc/passwd /etc/shadow /etc/group /etc/gshadow /var/log/messages |egrep "(i|a)" &&  echoYellow "关键的系统文件已锁定" || echoRed "文件未锁定" 
    echoYellow "----------------------------------------------"
    sleep 3
    echoYellow "----------------------------------------------"
    sleep 6

    systemctl restart sshd
#优化总计项
    echoGreen "--------------------------------------------------------------------------------------------------------"
    echoRed "服务器已初始化完毕，所做事情如下："
    echoRed "1:添加普通用户,更改命令提示符颜色及添加命令别名"
    echoRed "2:远程连接SSH服务优化"
    echoRed "3:配置国内yum源，并更新软件至最新，安装基础软件"
    echoRed "4:定时自动更新服务器时间"
    echoRed "5:关闭firewalld、selinux"
    echoRed "6:调整文件描述符的数量（ulimit）"
    echoRed "7:精简开机启动服务（rsyslog sshd.service network chronyd crond sysstat）"
    echoRed "8:内核参数优化"
    echoRed "9:更改字符集，支持中文，但建议还是用英文字符集，防止乱码"
    echoRed "10:清空/etc/issue && 清空/etc/motd"
    echoRed "11:清除多余的系统虚拟账号（nologin的，此优化不是必须的）"
    echoRed "12:为grub菜单加密---（阿里云等云平台不需要，自建机房或者虚拟机可以优化此项）"
    echoRed "13:命令历史记录优化"
    echoRed "14:更改主机名"
    echoRed "15:配置回收站"
    echoRed "16:安装监控系统并加入,这里选择的是zabbix（这里看企业选择什么监控系统）这不是优化系统哦"
    echoRed "17:系统优化项"
    echoRed "18:锁定关键系统文件-----(这些必须在最后一项进行初始化，因为我锁了文件会影响写入，会报错…………)"
    echoGreen "--------------------------------------------------------------------------------------------------------"
    echoGreen "初始化完成，建议手动重启服务器，让所有初始化参数生效"
    echoYellow "----------------------------------------------"
    echoYellow "----------------------------------------------"
    sleep 4

    echoRed "准备重启服务器………………………………"
    sleep 30
    reboot
}
